package com.tlx.image;

import java.util.ArrayList;
import java.util.List;

import com.tlx.core.util.RandomUtils;


public class ImageCutUtils {

    /**
     * 平均垂直切分图片，每个图片高度最大为maxH
     * 
     * @param imgPath
     * @param maxH
     * @return
     * @throws Exception
     */
    public static List<String> cutVerticalAverage(String imgPath, int maxH) {
        try {
            int[] size = ImageBaseUtils.getImgInfo(imgPath);
            // int w = size[0];
            int h = size[1];

            int count = h / maxH;
            int realH = 0;

            if (h % maxH != 0) {
                count++;
            }

            realH = h / count;

            if (realH != maxH && count > 1) {
                realH = realH + 1;// 加1像素，防止出现1像素以内的图片
            }

            return cutVertical(imgPath, realH);
        } catch (Exception e) {
            throw new RuntimeException("裁减图片失败【" + imgPath + "】", e);
        }
    }

    /**
     * 垂直拆分图片
     * 
     * @param imgPath
     * @param resizeH
     *            拆分高度
     * @return
     * @throws Exception
     */
    public static List<String> cutVertical(String imgPath, int resizeH) {
        try {
            List<String> resultList = new ArrayList<String>();

            int[] size = ImageBaseUtils.getImgInfo(imgPath);
            int w = size[0];
            int h = size[1];

            int count = h / resizeH;

            if (h % resizeH != 0) {
                count++;
            }
            
            for (int i = 0; i < count; i++) {
                String newPath = RandomUtils.randomName("cut-" + i, imgPath);

                ImageBaseUtils.cut(imgPath, newPath, w, resizeH, 0, i * resizeH);
                resultList.add(newPath);
            }
            return resultList;
        } catch (Exception e) {
            throw new RuntimeException("裁减图片失败【" + imgPath + "】", e);
        }
    }
}
